<?php

namespace App\Http\Controllers\Backstage;

use App\Http\Controllers\Backstage\BCommonController;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\DB;
use App\Models\CommonModel;
use App\Models\BackstageModel;
use Illuminate\Http\Request;
use App\Libary\Captcha\Code;
use Illuminate\Support\Facades\Validator;

// require_once '../app/libary/captcha/Code.class.php';

class AdminController extends BCommonController
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/backstage/admin/index';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    // 管理员列表首页
    public function index(){
        $list = BackstageModel::getAdminList();
        return view('backstage/admin/index',['list'=>$list]);
    }

    // 新增管理员
    public function add(){
        $group = DB::table('admin_group')->select(['id','role'])->orderBy('id','asc')->get();
        return view('backstage/admin/add',['group'=>$group]);
    }

    public function doadd(Request $request){
        // 验证
        if( $request->isMethod('POST') ){//表单请求是否是POST请求
            $info = $request->except('_token');// 请求数据中除了_token以外的值
            $count = CommonModel::getCount('admin',['user_name'=>$info['user_name']]);
            if($count>0) return response()->json(['status'=>'0','message'=>'用戶名已被使用！']);
            if( empty($info['user_name']) ){
                return response()->json(['status'=>'0','message'=>'請輸入用護名！']);
            }elseif(strlen($info['user_name'])<4 || strlen($info['user_name'])>20){
                return response()->json(['status'=>'0','message'=>'請輸入4-20個字符作為用戶名！']);
            }
            if( empty($info['user_pass']) ){
                return response()->json(['status'=>'0','message'=>'請輸入密碼！']);
            }elseif(strlen($info['user_pass'])<6 || strlen($info['pwd'])>20){
                return response()->json(['status'=>'0','message'=>'請輸入6-20個字符作為密碼！']);
            }
            if( empty($info['user_pass'])!=empty($info['user_pass_confirmation'])){
                return response()->json(['status'=>'0','message'=>'兩次輸入的密碼不壹致！']);
            }
            $data = array(
                'user_name' => trim($_POST['user_name']),
                'user_pass' => md5(base64_encode(trim($_POST['user_pass']))),
                'real_name' => trim($_POST['real_name']),
                'u_group_id' => intval($_POST['u_group_id']),
                'qq' => trim($_POST['qq']),
                'phone' => trim($_POST['phone']),
                'add_time' => time()
            );
            $newid = CommonModel::addDataGetId('admin',$data);

            if($newid){
                return response()->json(['status'=>'1','message'=>'操作成功！','jumpUrl'=>'/backstage/admin/index']);
            }else{
                return response()->json(['status'=>'0','message'=>'操作失败！']);
            }

        }
    }
    // 修改管理员
    public function edit($id){
        $info = CommonModel::getOne('admin',['id'=>intval($id)]);
        $group = DB::table('admin_group')->select(['id','role'])->orderBy('id','asc')->get();
        return view('backstage/admin/edit',['info'=>$info,'group'=>$group]);
    }
    public function doedit(Request $request){
        // 验证
        if( $request->isMethod('POST') ){// 表单请求是否是POST请求
            $info = $request->except('_token');// 请求数据中除了_token以外的值
            $id = intval($info['id']);
            $count = CommonModel::getCount('admin',['user_name'=>$info['user_name']]);
            $oldData = CommonModel::getOne('admin',['id'=>$id]);
            if($count>0 && $oldData->user_name!=$info['user_name'] ) return response()->json(['status'=>'0','message'=>'用戶名已被使用！']);
            if( empty($info['user_name']) ){
                return response()->json(['status'=>'0','message'=>'請輸入用護名！']);
            }elseif(strlen($info['user_name'])<4 || strlen($info['user_name'])>20){
                return response()->json(['status'=>'0','message'=>'請輸入4-20個字符作為用戶名！']);
            }
            $group = DB::table('admin_group')->select(['id','role'])->orderBy('id','asc')->get();
            foreach ($group as $key => $value) {
                $groupArr[$value->id] = $value->role;
            }
            // dd($groupArr);
            $data = array(
                'user_name' => trim($_POST['user_name']),
                'real_name' => trim($_POST['real_name']),
                'u_group_id' => intval($_POST['u_group_id']),
                'qq' => trim($_POST['qq']),
                'phone' => trim($_POST['phone']),
            );
            $cheInfo = ['user_name'=>'帳號','real_name'=>'真實姓名','u_group_id'=>'所屬用護組','qq'=>'QQ','phone'=>'電話號碼'];
            $res = CommonModel::updateData('admin',['id'=>$id],$data);
            if($res){
                $logContent='';
                foreach ($user as $key => $value) {
                    if($user[$key]!=$oldData->$key){
                        if($key=='u_group_id'){
                            $logContent.="将".$cheInfo[$key]."由:<b style='color:red'>".$groupArr[$oldData->$key]."</b>,修改为:<b style='color:red'>".$groupArr[$user[$key]]."</b>。";
                        }else{
                            $logContent.="将".$cheInfo[$key]."由:<b style='color:red'>".$oldData->$key."</b>,修改为:<b style='color:red'>".$user[$key]."</b>。";    
                        }
                    }
                }
                saveCommonLog($id, $logContent, 'user', session('admin')->real_name, session('admin')->id, 3);
                return response()->json(['status'=>'1','message'=>'操作成功！','jumpUrl'=>'/backstage/admin/index']);
            }else{
                return response()->json(['status'=>'0','message'=>'操作失败！']);
            }

        }
    }

    // 修改管理员密码
    public function edit_pass(){
        return view('backstage/admin/edit_pass');
    }
    public function doedit_pass(Request $request){
        // 验证
        if( $request->isMethod('POST') ){//表单请求是否是POST请求
            $info = $request->except('_token');// 请求数据中除了_token以外的值
            $id = session('admin')->id;
            $newPass = md5(base64_encode(trim($info['pass_new']))); 
            $pass = CommonModel::getField('admin','user_pass',['id'=>$id]);
            if($newPass!=$pass) return response()->json(['status'=>'0','message'=>'原密码错误']);
            if($count>0 && session('admin')->user_name!=$info['user_name']) return response()->json(['status'=>'0','message'=>'用戶名已被使用！']);
            if( empty($info['pass_new']) ){
                return response()->json(['status'=>'0','message'=>'請輸入密碼！']);
            }elseif(strlen($info['pass_new'])<6 || strlen($info['pass_new'])>20){
                return response()->json(['status'=>'0','message'=>'請輸入6-20個字符作為密碼！']);
            }
            if( empty($info['pass_new'])!=empty($info['pass_repeat'])){
                return response()->json(['status'=>'0','message'=>'兩次輸入的密碼不壹致！']);
            }
            $res = CommonModel::updateData('admin',['id'=>$id],['user_pass'=>$newPass]);
            if($res){
                return response()->json(['status'=>'1','message'=>'修改成功！','jumpUrl'=>'/backstage/admin/index']);
            }else{
                return response()->json(['status'=>'0','message'=>'修改失败！']);
            }

        }
    }




}
